package org.skyui.accesscontrol;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.baycrypt.server.beans.devices.DeviceBean;
import com.baycrypt.server.beans.people.UserBean;
import com.baycrypt.server.beans.people.UserGroupBean;
import com.baycrypt.vaadinui.VaadinUIApplication;

public class BeanAccessController {

	public static Collection<DeviceBean> getDevices(ControlledBean bean) {
		Map<String, UserBean> usersMap = new HashMap<String, UserBean>();
		Map<String, DeviceBean> devicesMap = new HashMap<String, DeviceBean>();

		Set<UserBean> users = bean.getAuthorizedUsers();

		if (users != null) {
			for (UserBean user : users) {
				usersMap.put(user.getId(), user);
			}
		}

		Set<UserGroupBean> groups = bean.getAuthorizedGroups();

		if (groups != null) {
			for (UserGroupBean group : groups) {
				Set<UserBean> groupUsers = group.getAuthorizedUsers();
				if (groupUsers != null) {
					for (UserBean user : groupUsers) {
						usersMap.put(user.getId(), user);
					}
				}
			}

		}

		for (UserBean user : usersMap.values()) {
			Set<DeviceBean> userDevices = user.getOwnedDevices();
			if (userDevices == null)
				continue;
			for (DeviceBean device : userDevices) {
				devicesMap.put(device.getId(), device);
			}
		}
		return devicesMap.values();
	}

	public static boolean checkUserSessionAccessControl(UserOwnedBean bean) {
		String role = VaadinUIApplication.getInstance().getRole();
		if (role.equals("ADMIN") || role.equals("ROOT") )
			return true;
		String userName = VaadinUIApplication.getInstance().getUserName();
		return userName.equals(bean.getOwner());
	}
}
